﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShExcelLib.Class
{
    public class ColumnConvert
    {
        /// <summary>
        /// 将A,B,C。。。转为0，1，2 地址中如带数字，将被忽略，如B2，将忽略掉2
        /// </summary>
        /// <param name="addr"></param>
        /// <returns></returns>
        public static int ColumnIndex(string addr)
        {
            addr = addr.ToUpper();
            var chars = (from c in addr where c >= 'A' && c <= 'Z' select c).ToArray();
            int num = 0;
            foreach(var c in chars)
            {
                num = num * 26 + (c - 'A'+1);
            }
            return num - 1;
        }

        /// <summary>
        /// 将数字转换为excel的列名，0->A, 1->B ....
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static string Index2Column(int num)
        {
            List<int> nums = new List<int>();
            do
            {
                int n1 = num / 26;  //( >0 )
                int n2 = num % 26;  //(0-25)
                nums.Add(n2);
                if (n1 == 0)
                {
                    var chars = (from n in nums select (char)('A' + n )).ToArray().Reverse();
                    return String.Join("", chars);
                }
                num = n1-1;
            } while (true);
        }
    }
}
